<template>
  <div id="changePwd">
    <el-dialog v-model="showPwdDialog" title="修改密码" width="500" :show-close="false" :append-to-body="false"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="pwdFormRef" :rules="pwdFormRule" :model="pwdForm" label-width="100px" class="form-input-l"
        :inline-message="true" size="default">
        <el-form-item prop="oldPwd" label="原密码">
          <el-input v-model="pwdForm.oldPwd" type="text" placeholder="请输入原密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="newPwd" label="新密码">
          <el-input v-model="pwdForm.newPwd" type="text" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="repeatPwd" label="重复密码">
          <el-input v-model="pwdForm.repeatPwd" type="text" placeholder="请再次输入新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmPassword(pwdFormRef)">保 存</el-button>
        <el-button @click="closePwdDialog(pwdFormRef)">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
//引入组件区 ===================================
import { ref, reactive, getCurrentInstance } from 'vue';
import type { FormInstance } from 'element-plus';
import { AppStore } from '../stores/store';
import { notifyType, notifyMessage } from '../utils/common';
import { Encrypt } from '../utils/crypto';
let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 定义变量区 ================================
let showPwdDialog = ref(false);
let pwdForm: any = reactive({
  oldPwd: '', //原密码
  newPwd: '', //新密码
  repeatPwd: '' //确认密码
});
let pwdFormRef = ref<FormInstance>();
let pwdFormRule = {
  oldPwd: [
    {
      required: true,
      message: '请输入原密码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  newPwd: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 20,
      message: '长度为6到20个字符',
      trigger: 'blur'
    },
    // { validator: validatePass, trigger: 'blur' }
  ],
  repeatPwd: [
    {
      required: true,
      validator: checkPassword,
      trigger: 'blur'
    }
  ]
};

// 使用方法区 =====================================
//暴露属性和方法
defineExpose({
  showChangePassword
});

// 验证新密码
function validatePass(rule: any, value: any, callback: any) {
  const regex = /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,20}/g;
  if (!regex.test(value)) {
    callback(new Error('密码必须包含大小写字母、数字、特殊字符'));
    return;
  }

  //不能相同字符（如111、aaa）连续3位或3位以上
  const regSame = /(\w)*(\w)\2{2}(\w)*/g;
  if (regSame.test(value)) {
    callback(new Error('密码不能出现3位或3位以上的连续相同字符'));
    return;
  }
  //不能连续字符（如123、abc）连续3位或3位以上
  if (!continueSameStr(value)) {
    callback(new Error('密码不能出现3位或3位以上的连续的顺序字符'));
    return;
  }
  callback();
}

//不能连续字符（如123、abc）连续3位或3位以上
function continueSameStr(str: any) {
  const arr = str.split('');
  let flag = true;
  for (let i = 1; i < arr.length - 1; i++) {
    const firstIndex = arr[i - 1].charCodeAt();
    const secondIndex = arr[i].charCodeAt();
    const thirdIndex = arr[i + 1].charCodeAt();
    if (thirdIndex - secondIndex === 1 && secondIndex - firstIndex === 1) {
      flag = false;
    }
  }
  return flag;
}

// 两次密码输入保持一致
function checkPassword(rule: any, value: any, callback: any) {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== pwdForm.newPwd) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
}

//修改密码保存
function confirmPassword(formRef: any) {
  if (!formRef) return;
  formRef.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const obj = {
      id: store.userInfo.id,
      oldPwd: pwdForm.oldPwd,//Encrypt(pwdForm.oldPwd)
      newPwd: pwdForm.newPwd,//Encrypt(pwdForm.newPwd)
      repeatPwd: pwdForm.repeatPwd,//Encrypt(pwdForm.repeatPwd)
      systemUsers: store.userInfo.systemUsers,
      changeType: 1
    };
    const url = '/api/user/changePassword';
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          showPwdDialog.value = false;
          clearPWDialog();
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
      });
    return true;
  });
}

// 显示修改密码的弹框
function showChangePassword() {
  showPwdDialog.value = true;
}

//关闭修改密码
function closePwdDialog(formRef: any) {
  formRef.clearValidate();
  clearPWDialog();
  showPwdDialog.value = false;
}
function clearPWDialog() {
  pwdForm.oldPwd = '';
  pwdForm.newPwd = '';
  pwdForm.repeatPwd = '';
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: end;

  .el-button {
    width: 50px;
    padding: 10px;
    margin: 10px;
  }
}
</style>